using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;



public class UiManager : MonoBehaviour {

    [SerializeField]
    Image m_lifebar;

    [SerializeField]
    AnimationCurve m_lifeUpdateCurve;

    [SerializeField]
    GameObject m_gameOverScreen;

    Coroutine m_updateLifeCoroutine;

    float m_lifebarMaxSize;
    Dave m_dave;

    GameManager m_gameManager;

    [SerializeField]
    GameObject CaracteristicMenu;

    [SerializeField]
    Image[] m_boats;

    int currentBoat = 0;


	// Use this for initialization
	void Start ()
    {
        m_lifebarMaxSize = m_lifebar.rectTransform.localScale.x;
        m_dave = FindObjectOfType<Dave>();
        m_dave.onLifeUpdated.AddListener(UpdateLifeBar);
        m_dave.onRandomBoat.AddListener(RandomBoat);
        m_dave.onRandomBoatStop.AddListener(DisableBoats);
	}

    public void restartLevel()
    {
        GameManager.m_currentRoom = 0;
        GameManager.m_caracteristics = null;
        SceneManager.LoadScene("MainScene", LoadSceneMode.Single);
    }

    public void RestartLastRoom()
    {
        SceneManager.LoadScene("MainScene", LoadSceneMode.Single);
    }

    public void GameOver()
    {
        m_gameOverScreen.SetActive(true);
    }
	
    void UpdateLifeBar(float lifeRemaining)
    {
        float x = (lifeRemaining * m_lifebarMaxSize) / 100;

        if (m_updateLifeCoroutine != null)
            StopCoroutine(m_updateLifeCoroutine);

        m_updateLifeCoroutine = StartCoroutine(UpdatingLife(x));
    }

    IEnumerator UpdatingLife(float xValue)
    {
        float time = 0;
        float wantingTIme = 1;
        float initialX = m_lifebar.transform.localScale.x;

        while(time < wantingTIme)
        {
            float x = Mathf.Lerp(initialX, xValue, m_lifeUpdateCurve.Evaluate(time / wantingTIme));
            m_lifebar.transform.localScale = new Vector3(x, 1, 1);
            time += Time.deltaTime;
            yield return null;
        }

        m_updateLifeCoroutine = null;
    }

    public void ActiveCaracChoices()
    {
        CaracteristicMenu.SetActive(true);
        CaracteristicMenu.GetComponent<CaracteristicsChoices>().OnOpenCaracMenus();
    }


    public void quit()
    {
        Application.Quit();
    }

    public void RandomBoat()
    {
        m_boats[currentBoat].gameObject.SetActive(true);

        if (currentBoat != m_boats.Length - 1)
            currentBoat++;
        else
            currentBoat = 0;
    }

    public void DisableBoats()
    {
        for (int i = 0; i < m_boats.Length; i++)
            m_boats[i].gameObject.SetActive(false);
    }

}
